39&40. 组合总和

39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例 2:

输入:candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

提示:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都是独一无二的。
  • 1 <= target <= 500

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum


思路及算法

我看到『组合』两个字,第一反应就是『回溯算法』,看了下题目标签果然是。

分析题目:

  1. candidates是候选列表,我们需要从这个候选列表选择元素
  2. 选的所有元素的和等于target,初略理解为sum(track) == target退出
  3. candidates 中的数字可以无限制重复被选取。

画出完整决策图

例子: candidates = [2,3,6,7], target = 7

首先,根据题目信息在纸上画一画『决策图』

观察决策树并剪枝

对候选数组排序

为了方便剪枝,需要先对candidates进行升序排序

过滤重复组合

关于23满足等于target的组合有 [2, 2, 3] [2, 3, 2]等等

可以简单的思考下,将获取到的[2, 3, 2] 排序之后就是[2, 2, 3],所以只要判定在排序之后的结果是已经存在的,那么就直接跳过

剪掉大于等于target之后的分支

  • 当前组合和等于target

[2, 2, 3]这个组合当前是满足条件的,回溯一次之后是 [2, 2],当再次进行选择时,由于之前进行排序,所以这个候选数组是单调递增的,所以选择3之后的值所构成的和肯定是大于target的,直接剪掉

  • 当前组合和大于target

这里的大于,肯定组合和是第一次大于target的时候,同理依据数组单调递增的特性,直接剪掉

现在的决策图就是变成了这样:

39-代码1

根据上方的分析,就可以写出如下代码:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        # 结果数组
        result = []
        # 升序排序
        candidates = sorted(candidates)
        
        def dfs(candidates, target, track):
            # 组合和相等且排序之后的组合不存在结果数组中 就可以加入进去
            if sum(track) == target and sorted(track) not in result:
                result.append(track[:])
                return True
            elif sum(track) > target:
                return True
            # 组合和大于等于target,返回一个布尔值,方便后面回溯

            
            for option in candidates:
                # 选择元素
                track.append(option)
                # 进入下一层决策
                x = dfs(candidates, target, track)
                # 回溯
                track.pop()
                # 如果为True,后面的元素都是不符合的了,可以直接再次回溯到上一层
                # 正常结束的递归,返回的是None
                if x:
                    break
        dfs(candidates, target, [])
        return result

上方的题解,可以顺利AC,但是效率很低。我们可以再次进行优化。

优化

主要的耗时还是在于剪枝上,对于[2, 2, 3][2, 3, 2],我们如何判定的重复。

即便 [2, 3, 2]是重复组合,我们还是需要完整的将它找出来,然后才来比对

能不能在完全找出来之前,就可以知道现在走的这条路径会是重复项,提前撤出来

优化点:因为候选数组单调递增的性质,所以第一次找到的组合必定是单调递增的

换句话说,当前路径的组合一旦出现非递增情况就直接跳过。选出的元素如果小于已选择路径数组中的最后一位元素,即出现非递增,可跳过

if len(track) >= 1 and option < track[-1]:
	continue

39-代码2

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates = sorted(candidates)
        def dfs(candidates, target, track):
            # if sum(track) == target and sorted(track) not in result:
            if sum(track) == target:
                result.append(track[:])
                return True
            elif sum(track) > target:
                return True

            
            for option in candidates:
                if len(track) >= 1 and option < track[-1]:
                    continue
                track.append(option)
                x = dfs(candidates, target, track)
                track.pop()
                if x:
                    break
        dfs(candidates, target, [])
        return result

更优解

翻了题解,又看到了更优解,大佬不亏是大佬,O(∩_∩)O哈哈~

我写的算法,是从0开始加,大佬们写的是从target开始减

题解: 回溯算法 + 剪枝(是否需要剪枝看实际情况,通常要剪枝)

39-代码3

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        size = len(candidates)
        if size == 0:
            return []

        # 剪枝是为了提速,在本题非必需
        candidates.sort()
        # 在遍历的过程中记录路径,它是一个栈
        path = []
        res = []
        # 注意要传入 size ,在 range 中, size 取不到
        self.__dfs(candidates, 0, size, path, res, target)
        return res

    def __dfs(self, candidates, begin, size, path, res, target):
        # 先写递归终止的情况
        if target == 0:
            # Python 中可变对象是引用传递,因此需要将当前 path 里的值拷贝出来
            # 或者使用 path.copy()
            res.append(path[:])
            return

        for index in range(begin, size):
            residue = target - candidates[index]
            # “剪枝”操作,不必递归到下一层,并且后面的分支也不必执行
            if residue < 0:
                break
            path.append(candidates[index])
            # 因为下一层不能比上一层还小,起始索引还从 index 开始
            self.__dfs(candidates, index, size, path, res, residue)
            path.pop()

40. 组合总和(2)

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii


此题相比较 39 多了一个约束条件——candidates 中的每个数字在每个组合中只能使用一次。

所以,我们可以单独定义一个数组used记录每个元素的使用情况,如果已被使用就跳过去选择下一位

代码2 再添加一些条件就可以啦!

这两道题的解法与 46&47. 组合排列 及其类似

40-代码1

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        
        def dfs(candidates, target, track, used):

            if sum(track) == target:
                result.append(track[:])
                return True
            elif sum(track) > target:
                return True
            

            for index, option in enumerate(candidates):
                if index >= 1 and candidates[index-1] == option and not used[index-1] :
                    continue
                if len(track) >= 1 and option < track[-1]:
                    continue
                if not used[index]:
                    track.append(option)
                    used[index] = True
                    x = dfs(candidates, target, track, used)
                    track.pop()
                    used[index] = False
                    if x:
                        break
        dfs(sorted(candidates), target, [], [False for _ in range(len(candidates))])
        return result

这道的揭发同样有从target开始减,直到为0

题解: 回溯算法 + 剪枝

40-代码2

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        def dfs(begin, path, residue):
            if residue == 0:
                res.append(path[:])
            
            for index in range(begin, size):
                if candidates[index] > residue:
                    break
                
                if index > begin and candidates[index] == candidates[index-1]:
                    continue
                path.append(candidates[index])
                # 当前元素已被选择,下一层选择从这个元素后面开始选 index+1
                dfs(index+1, path, residue)
                path.pop()
		res = []
        size = len(candidates)
        if not size:
            return []
       	candidates.sort()
       	dfs(0, [], target)
        return res